package xyz.icxl.android.architecture.observer

import androidx.lifecycle.Observer
import xyz.icxl.android.architecture.ui.mvvm.BaseViewModel

class DslAPIRequestStatus<T>(listener: ListenerBuilder<T>.() -> Unit) :
    Observer<BaseViewModel.APIRequestStatus<T>> {

    private val mListener: ListenerBuilder<T>

    init {
        mListener = ListenerBuilder<T>().also(listener)
    }

    override fun onChanged(t: BaseViewModel.APIRequestStatus<T>?) {
        if (t?.requestIng == true) {
            mListener.requestIng?.invoke()
        }
        if (t?.requestFail?.isNotEmpty() == true) {
            mListener.requestFail?.invoke(t.requestFail)
        }
        if (t?.requestSuccess != null) {
            mListener.requestSuccess?.invoke(t.requestSuccess)
        }
    }

    class ListenerBuilder<T> {
        internal var requestIng: (() -> Unit)? = null
        internal var requestSuccess: ((T) -> Unit)? = null
        internal var requestFail: ((String) -> Unit)? = null

        fun onRequestIng(action: () -> Unit) {
            requestIng = action
        }

        fun onRequestSuccess(action: (T) -> Unit) {
            requestSuccess = action
        }

        fun onRequestFail(action: (String) -> Unit) {
            requestFail = action
        }

    }

}